package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private AccountClient accountClint;

    @Transactional          // 控制本地事务
    @GlobalTransactional    //启动全局事务,只在第一个模块添加
    @Override
    public void create(Order order) {
        //TOOO:远程调用发号器,生成订单id

        //临时随机产生一个id,完成发号器删除这行代码
        Map<String,String> m = easyIdClient.nextId("order_business");
        long orderId =Long.valueOf(m.get("data"));

        order.setId(orderId);
        orderMapper.create(order);

        // TOOO:远程调用库存,减少库存
        storageClient.decrease(order.getProductId(),order.getCount());
        // TOOO:远程调用账户,扣减金额
        //accountClint.decrease(order.getUserId(),order.getMoney());
    }
}
